package com.abcdefg.java_chatroom.api;


import com.abcdefg.java_chatroom.mapper.UserMapper;
import com.abcdefg.java_chatroom.model.User;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("UserApi")
public class UserApi {

    @Autowired
    private UserMapper userMapper;


    @PostMapping("login")
    private Object login(String username, String password, HttpServletRequest request) {
        User user = userMapper.selectUserByName(username);
        if(user == null || !user.getPassword().equals(password)){
            return new User();
        }
        //如果创建成功，则创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    @PostMapping("register")
    private Object register(String username, String password){
        User user;
        try{
            user= new User();
            user.setUserName(username);
            user.setPassword(password);
            userMapper.addUser(user);

            System.out.println("注册成功！");
        }catch(DuplicateKeyException e){
            System.out.println("注册失败！");
            user=new User();
        }
        user.setPassword("");
        return user;
    }

    @GetMapping("userInfo")
    @ResponseBody
    private Object getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session == null){
            System.out.println("当前获取不到session对象！！！");
            return new User();
        }
        User user = (User)session.getAttribute("user");
        if(user == null){
            System.out.println("当前获取不到user对象");
            return new User();
        }
        System.out.println("用户信息：" + user.toString());
        user.setPassword("");
        return user;
    }
}
